/*
 * Copyright The OpenTelemetry Authors
 * SPDX-License-Identifier: Apache-2.0
 */

package com.xiashitech.agent.instrumentation.dubbo.common.inst.internal;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.Result;
import com.xiashitech.agent.instrumentation.dubbo.common.inst.DubboRequest;
import io.opentelemetry.javaagent.shaded.instrumentation.api.instrumenter.network.ClientAttributesGetter;
import io.opentelemetry.javaagent.shaded.instrumentation.api.instrumenter.network.ServerAttributesGetter;
//import io.opentelemetry.javaagent.shaded.instrumentation.api.instrumenter.net.InetSocketAddressNetClientAttributesGetter;

import javax.annotation.Nullable;
import java.net.InetSocketAddress;

// TODO: TO DEL ON NEXT Version (OTEL 版本升级变更 1.29.0)
//public final class DubboNetClientAttributesGetter
//    extends InetSocketAddressNetClientAttributesGetter<DubboRequest, Result> {
//
//  @Override
//  @Nullable
//  public InetSocketAddress getAddress(DubboRequest request, @Nullable Result response) {
//    InetSocketAddress address = request.getRemoteAddress();
//    if (address == null) {
//      URL url = request.getUrl();
//      address = InetSocketAddress.createUnresolved(url.getHost(), url.getPort());
//    }
//    return address;
//  }
//
//  @Override
//  @Nullable
//  public String transport(DubboRequest request, @Nullable Result response) {
//    return null;
//  }
// }


// 特别说明：OTEL 开源版 在NetClientAttributesGetter实现的是 Server 接口；DubboNetworkServerAttributesGetter是同时实现的 Server 接口 和 Client 接口
public final class DubboNetClientAttributesGetter implements ClientAttributesGetter<DubboRequest, Result>, ServerAttributesGetter<DubboRequest, Result> {

  @Nullable
  @Override
  public String getClientAddress(DubboRequest request) {
    return request.getUrl().getHost();
  }

  @Nullable
  @Override
  public Integer getClientPort(DubboRequest request) {
    return request.getUrl().getPort();
  }

  @Override
  @Nullable
  public InetSocketAddress getClientInetSocketAddress(DubboRequest request, @Nullable Result result) {
    InetSocketAddress address = request.getRemoteAddress();
    if (address == null) {
      URL url = request.getUrl();
      address = InetSocketAddress.createUnresolved(url.getHost(), url.getPort());
    }
    return address;
  }


}
